package main

import (
	"fmt"
	"sync"
	"time"
)

func main1() {
	total := 0
	ch := make(chan int)
	ch <- total

	for i := 0; i < 1000; i++ {
		go func() {
			ch <- <-ch + 1
		}()
	}
	time.Sleep(time.Second)
	fmt.Println(<-ch)
}

func main2() {
	total := 0
	ch := make(chan int)

	go func() {
		ch <- total
	}()

	ch <- <-ch + 1
}

func worker(id int, c chan int) {

	time.Sleep(time.Second * 1)
	c <- id
}

func main() {
	start := time.Now()
	c := make(chan int)
	wg := sync.WaitGroup{}

	for i := 0; i < 5; i++ {
		wg.Add(1)
		go func(i int) {
			defer wg.Done()
			worker(i, c)
		}(i)
	}
	go func() {
		wg.Wait()
		close(c)
	}()
	// for i := 0; i < 5; i++ {
	// 	fmt.Println(<-c)
	// }

	for {
		v, ok := <-c
		if !ok {
			end := time.Now()
			fmt.Println(end.Sub(start))
			break
		}
		fmt.Println(v)
	}

}
